<!--
*
* 忘记密码
*
*
*
-->
<template>
    <el-dialog 
    v-model="dialogVisible" 
    title="找回密码"
    width="25%" 
    :close-on-click-modal="false" 
    :close-on-press-escape="true"
    @closed="resetForm(retrieveRef)">
        <template #main>
            <el-form :model="retrieveForm" label-position="top" size="large" ref="retrieveRef" :rules="rules">
                <!-- <el-form-item label="邮箱/手机号" prop="condition"> -->
                <el-form-item label="邮箱" prop="condition">
                    <el-input v-model.trim="retrieveForm.condition" placeholder="" ></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="verificationCode"  class="code-item">
                    <el-input v-model.trim="retrieveForm.verificationCode" placeholder="">
                        <template #append>
                            <el-button :disabled="codeDisabled" @click="onSendCode">{{ emailCode }}</el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="password">
                    <el-input type="password" v-model.trim="retrieveForm.password" @keyup.enter="onSubmit" placeholder=""></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <span class="footer">
                <el-button class="submig-btn" @click="onSubmit" :loading="submitLoading">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
  
<script setup>
import { reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

import { loginApi } from '@/api/system/login/login-api';
import { usersApi } from '@/api/system/users/users-api';
import { SEND_EMAIL_TYPE } from '@/constants/system/email-const';

import { aes } from '@/utils/crypto-util';
import { PHONE_REGEXP, EMAIL_REGEXP } from '@/utils/verify-util';
import { countDown, clearCountDown } from '@/utils/countdown-util';
// ========================= 找回密码 =========================
const retrieveRef = ref();
let dialogVisible = ref(false);
let submitLoading = ref(false);
const retrieveForm = reactive({
    condition:'',
    eMail:'', // 邮箱
    phoneNumber:'', // 手机号
    verificationCode:'', // 验证码
    password:'', // 新密码
});
// 邮箱/手机号校验
// const conditionValidator = (rule, value, callback) => {
//      if(PHONE_REGEXP.test(value) || EMAIL_REGEXP.test(value)) {
//         callback();
//     }else {
//         callback(new Error('请输入正确的邮箱或手机号'));
//     };
// };
const rules = reactive({
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'change' }
    ],
    condition: [
        // { required: true, message: '请输入邮箱或手机号', trigger: 'blur' },
        // {validator: conditionValidator, trigger: 'change'},
        // 现在仅支持邮箱
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
});

// 打开弹框
const onShowPassword = () => {
    dialogVisible.value = true;
}
// 组件向外暴露属性或方法
defineExpose({
    onShowPassword
});

// 更改密码
async function onSubmit() {
    retrieveRef.value.validate(async (valid) => {
        try {
            if(valid) {
                submitLoading.value = true;
                let date = new Date();
                // 判断是邮箱还是手机号
                const valueType = PHONE_REGEXP.test(retrieveForm.condition);
                valueType ? retrieveForm.phoneNumber = retrieveForm.condition : 
                retrieveForm.eMail = retrieveForm.condition;
                let form = {};
                form = {...form, ...retrieveForm};
                form.password = aes.en(form.password);
                form.updateAt = date;
                const res = await usersApi.resetPassword(form);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                ElMessage.success(res.meta.msg);
                dialogVisible.value = false;
            }
        } catch (e) {
            console.error(e);
            ElMessage.error(e.message)
        } finally {
            submitLoading.value = false;
        }
    })
};

let emailCode = ref('发送');
let codeDisabled = ref(false); // 按钮控制
// 验证码发送
async function onSendCode() {
    try {
        if(!retrieveForm.condition) {
            // ElMessage.error('请输入邮箱或手机号');
            ElMessage.error('请输入邮箱地址');
            return false;
        };
        codeDisabled.value = true; // 发送按钮控制
        let countDownNum = 60;// 倒计时
        countDown(countDownNum, (dataNum) => {
            if(typeof dataNum == "object") {
                emailCode.value = '发送';
                codeDisabled.value = false;
                return;
            };
            emailCode.value = dataNum;
        });
        // 验证码接口
        const res = await loginApi.emailSend({
            sendType:SEND_EMAIL_TYPE.UPDATE_PASSWORD.value, // 修改密码
            // eMail:retrieveForm.eMail,
            eMail:retrieveForm.condition,
        });
        if(res.meta.status !== 200) throw new Error(res.meta.msg);
    } catch (e) {
        console.error(e);
        ElMessage.error(e.message);
    }
};

// 关闭弹框后
function resetForm(refFormName) {
    if(!refFormName) return;
    refFormName.resetFields(); // 重置表单
    emailCode.value = '发送';
    clearCountDown();
};
</script>
  
<style scoped lang="scss">
    @import '@/theme/animations.scss';
    @import './update-password.scss';
</style>
  
